Nim Magic

This notebook explores making a cell magic for nim.

First, we load libs that we will need for defining an IPython magic:

In [12]:
from IPython.core.magic import register_line_cell_magic
In [ ]:
Now, we construct a file that contains nim code:
In [13]:
%%file default.nim

# This is a comment
echo("What's your name? ")
var name: string = "Kevin"
echo("Hi, ", name, "!")
Overwriting default.nim

Can we run the file and view the results?

In [14]:
import subprocess
import sys
p = subprocess.Popen(["nim", "compile", "--run", "default.nim"], stdout=subprocess.PIPE)
out, err = p.communicate()
if err:
    print(err.decode("utf-8"), file=sys.stderr)
if out:
    print(out.decode("utf-8"))
What's your name? 
Hi, Kevin!
/etc/nim.cfg(53, 2) Hint: added path: '/home/dblank/.babel/pkgs/' [Path]
/etc/nim.cfg(54, 2) Hint: added path: '/home/dblank/.nimble/pkgs/' [Path]
Hint: used config file '/etc/nim.cfg' [Conf]
Hint: system [Processing]
Hint: default [Processing]
[Linking]
Hint: operation successful (9000 lines compiled; 0.144 sec total; 14.148MB; Debug Build) [SuccessX]
/home/dblank/default 

In [ ]:
Now, we put that together into a cell magic:
In [20]:
@register_line_cell_magic
def nim(line, cell):
    fp = open("default.nim", "w")
    fp.write(cell)
    fp.close()
    p = subprocess.Popen(["nim", "compile", "--run", "default.nim"], stdout=subprocess.PIPE)
    out, err = p.communicate()
    if err:
        print(err.decode("utf-8"), file=sys.stderr)
    if out:
        print(out.decode("utf-8"))    

And now test it out:

In [21]:
%%nim 

type Animal = ref object of RootObj
  name: string
  age: int
method vocalize(this: Animal): string = "..."
method ageHumanYrs(this: Animal): int = this.age

type Dog = ref object of Animal
method vocalize(this: Dog): string = "woof"
method ageHumanYrs(this: Dog): int = this.age * 7

type Cat = ref object of Animal
method vocalize(this: Cat): string = "meow"


var animals: seq[Animal] = @[]
animals.add(Dog(name: "Sparky", age: 10))
animals.add(Cat(name: "Mitten", age: 10))

for a in animals:
  echo a.vocalize()
  echo a.ageHumanYrs()
woof
70
meow
10
/etc/nim.cfg(53, 2) Hint: added path: '/home/dblank/.babel/pkgs/' [Path]
/etc/nim.cfg(54, 2) Hint: added path: '/home/dblank/.nimble/pkgs/' [Path]
Hint: used config file '/etc/nim.cfg' [Conf]
Hint: system [Processing]
Hint: default [Processing]
CC: default
CC: system
[Linking]
Hint: operation successful (9017 lines compiled; 0.791 sec total; 14.148MB; Debug Build) [SuccessX]
/home/dblank/default